PHP Tutorial
PHP cookie is a small piece of information which is stored at client browser. It is used to recognize the user.
Cookie is created at server side and saved to client browser.
Each time the same computer requests a page with a browser, it will send the cookie too.
With PHP, you can both create and retrieve cookie values.
PHP provided setcookie() function to set a cookie.
This function requires upto six arguments and should be called before <html> tag
setcookie(name, value, expire, path, domain, secure, httponly);
name : This sets the name of the cookie
Value : This sets the value of the named variable
expire:It is used to set the expiry timestamp of the cookie
path: It is used to specify the path on the server for which the cookie will be available.
domain: It is used to specify the domain for which the cookie is available.
security: It is used to indicate that the cookie should be sent only if a secure HTTPS connection exists.
Following example will create two cookies name and age these cookies will be expired after one hour.
<?php
setcookie("name", "Will Smith", time()+3600, "/","", 0);
setcookie("age", "36", time()+3600, "/", "", 0);
?>
to check whether a cookie is set or not, the PHP isset() function is used.
<?php
if( isset($_COOKIE["name"]))
echo "Name = " . $_COOKIE["name"] . "<br>";
else
echo "Sorry... Not recognized" . "<br>";
?>
This will produce the following result −
Name = Will Smith.
For accessing a cookie value, the PHP $_COOKIE superglobal variable is used.
<?php
echo "Name = " . $_COOKIE["name"] . "<br>";
echo "Age = " . $_COOKIE["age"] . "<br>";
?>
This will produce the following result −
Name = Will Smith
Age = 36
To delete a cookie, use the setcookie() function with an expiration date in the past.
<?php
setcookie( "name", "", time()- 60, "/","", 0);
setcookie( "age", "", time()- 60, "/","", 0);
?>